﻿using System.Collections.Generic;
using System.Globalization;
using System.Security;
using System.Web.Mvc;
using SweetSurvey.Models.Repositories;
using SweetSurvey.Models.ViewModels;

namespace SweetSurvey.Controllers
{
    public class HomeController : ControllerBase
    {
        private ISurveyRepository surveyRepository;
        private IParticipatorRepository participatorRepository;

        #region Constructors

        public HomeController(ISurveyRepository surveyRepository, IParticipatorRepository participatorRepository)
        {
            this.surveyRepository = surveyRepository;
            this.participatorRepository = participatorRepository;
        }

        #endregion

        public ActionResult Index(string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl))
            {
                // no return url
                ViewBag.ReturnUrl = string.Empty;
            }
            else if (!Url.IsLocalUrl(returnUrl))
            {
                // open redirection attacks
                throw new SecurityException(string.Format(
                    CultureInfo.InvariantCulture,
                    "Open Redirection Attacks detected: ReturnUrl = {0}",
                    returnUrl));
            }
            else
            {
                // return url
                ViewBag.ReturnUrl = returnUrl;
            }
            return View();
        }

        [Authorize]
        public ActionResult MySurveys()
        {
            var models = this.surveyRepository.GetSurveysByEditorId(User.Identity.Name);
            var viewModels = new List<SurveyViewModel>();
            foreach (var s in models)
            {
                viewModels.Add(new SurveyViewModel(s, this.participatorRepository));
            }
            return View(viewModels);
        }

        [Authorize]
        public ActionResult DeleteSurvey(string id)
        {
            this.surveyRepository.AssertOwner(id, this.User.Identity.Name);
            this.surveyRepository.Delete(id);
            return Content("success");
        }

        public ActionResult About()
        {
            return View();
        }
    }
}
